package com.cg.service.impl;

import com.cg.common.CardCommon;
import com.cg.service.NumService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @ClassName NumServiceImpl
 * @Description TODO
 * @Author CG
 * @Date 2024/1/3 13:25
 **/
public class NumServiceImpl implements NumService {

    //宽
    @Value("${width}")
    private Integer width;
    //高
    @Value("${height}")
    private Integer height;
    //输出格式
    @Value("${format}")
    private String format;
    //输出路径
    @Value("${pathStr}")
    private String pathStr;

    /**
     * 生成条形码
     */
    @Override
    public String createBarCode(String cardNum) {
        //生成条形码也就是对流的操作--Writer---Code128Writer--输出文件
        Code128Writer code128Writer = new Code128Writer();
        //字节矩阵
        BitMatrix bitMatrix = code128Writer.encode(cardNum,BarcodeFormat.CODE_128,width,height);
        //文件输出的名字，前缀+id+后缀
        String fileName = CardCommon.BAR_CODE+cardNum+"."+format;
        String pathWriter = pathStr+fileName;
        Path path = Paths.get(pathWriter);
        try {
            MatrixToImageWriter.writeToPath(bitMatrix,format,path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 生成二维码
     */
    @Override
    public String createCode(String cardNum) {
        //对流的操作，Writer--MultiFormatWriter
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        //文件的名字
        String fileName = CardCommon.CODE +cardNum+"."+format;
        String pathWriter = pathStr+fileName;
        try {
            BitMatrix bitMatrix = multiFormatWriter.encode(cardNum, BarcodeFormat.QR_CODE, width, width);

            Path path = Paths.get(pathWriter);
            MatrixToImageWriter.writeToPath(bitMatrix,format,path);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }
}
